var app = getApp();
var util = require('../../utils/util.js');
Page({

  data: {
    //喵文对象
    talk: null,
    //相关喵文
    talkList: [],
    talkList1: [],
    talkList2: [],
    //举报类型
    complaninList: ['色情低俗', '政治敏感', '违反犯罪', '造谣传谣，涉嫌欺诈', '内容引起不适', '内容不适合未成年观看'],
    //是否全屏
    fullScreen: false,
    //弹出键盘
    focus: false,
    //键盘类型 1写一级评论2写二级评论3回复2级评论
    focusType: 1,
    //评论内容
    content: '',
    //后台拿到的评论列表
    commentList: [],
    //需要排除查询的一级评论id
    notInOneCommentIds: [],
    //第几次点击查看更多评论
    getOneCount: 0,
    //给哪一个一级评论添加二级评论
    oneComment: null,
    //一级评论个数
    oneAllQuantity: 0,
    //给哪一个二级评论写回复
    twoCommentIndex: null,

  },

  onLoad: function(options) {
    //找到系统状态位置
    this.setData({
      statusBarHeight: app.globalData.systemInfo.statusBarHeight + 15,
      windowHeight: app.globalData.systemInfo.windowHeight,
      plainText: app.globalData.user.plainText
    })

    //获取喵文详情
    this.getTalkInfo(options.id);
  },

  //转发
  onShareAppMessage: function(e) {
    var type = e.from;
    //从按钮转发
    if (type == 'button') {

      var talk = this.data.talk;
      //截取喵文内容
      var describe = talk.talkDescribe.substring(0, 15);
      //喵文类型
      var talkType = talk.talkType;
      //喵文id
      var id = talk.talkId;
      var resourceUrl = '';
      if (talkType == '0') {
        //喵文图片
        resourceUrl = talk.resourceList[0].src;
      } else {
        resourceUrl = talk.resourceList[0].src + "?x-oss-process=video/snapshot,t_1000,f_jpg,w_" + talk.resourceList[0].width + ",h_" + talk.resourceList[0].height + ",m_fast"
      }
      var share = {
        page: 'talkInfo',
        parame: {
          id: id
        }
      }
      return {
        title: describe,
        path: 'pages/index/index?share=' + JSON.stringify(share),
        imageUrl: resourceUrl
      }
    } else {
      //从胶囊转发,随机转发语句和图片
      var share = util.randomShare();
      return {
        title: share.title,
        path: 'pages/index/index',
        imageUrl: share.imageUrl
      }
    }
  },
  //弹出输入框
  openFocus: function(e) {
    var focusType = e.currentTarget.dataset.type;
    this.setData({
      focusType: focusType,
      focus: true
    })
    if (focusType == 2) {
      var index = e.currentTarget.dataset.index;
      var oneComment = this.data.commentList[index];
      oneComment.index = index;
      this.data.oneComment = oneComment;
    }
    if (focusType == 3) {
      var pindex = e.currentTarget.dataset.pindex;
      var index = e.currentTarget.dataset.index;
      var twoCommentIndex = {
        pindex: pindex,
        index: index
      }
      this.setData({
        twoCommentIndex: twoCommentIndex
      })
    }
  },
  //关闭输入框
  closeFocus: function() {
    this.setData({
      focus: false
    })
  },

  //评论
  comment: function(e) {
    var type = this.data.focusType;
    var content = this.data.content;
    this.setData({
      focus: false,
      content: ''
    })
    if (content == '') {
      return;
    }
    if (type == 1) {
      //创建一条新评论
      var comment = {
        oneCommentContent: content,
        oneCommentDate: "",
        oneShowDate: '刚刚',
        oneCommentId: util.getUUID(),
        oneCommentQuantity: 0,
        oneCommentUserId: this.data.plainText,
        oneHeadPortrait: app.globalData.user.headPortrait,
        oneLikeDate: null,
        oneLikeQuantity: 0,
        oneShowLikeQuantity: 0,
        oneNikeName: app.globalData.user.nikeName,
        talkId: this.data.talk.talkId,
        twoCommentResponseList: []
      }
      var commentList = this.data.commentList;
      //添加到评论第一个
      commentList.unshift(comment);
      //给评论数+1
      var talk = this.data.talk;
      talk.commentQuantity = talk.commentQuantity + 1;
      talk.showCommentQuantity = util.formatQuantity(talk.commentQuantity);
      //下次查询不查询新增加的
      var notInOneCommentIds = this.data.notInOneCommentIds;
      notInOneCommentIds.push(comment.oneCommentId);
      this.setData({
        commentList: commentList,
        talk: talk,
        notInOneCommentIds: notInOneCommentIds,
        noComment: true
      })
      this.addOneComment(content, comment.oneCommentId);
    } else if (type == 2) {
      var oneComment = this.data.oneComment;
      var id = util.getUUID()
      var newTwoComment = {
        twoCommentContent: content,
        showCommentDate: "刚刚",
        twoCommentId: id,
        twoCommentUserId: this.data.plainText,
        twoLikeDate: null,
        twoLikeQuantity: 0,
        twoShowLikeQuantity: util.formatQuantity(0),
        twoOneCommentId: oneComment.oneCommentId,
        twoUserHeadPortrait: app.globalData.user.headPortrait,
        twoUserNikeName: app.globalData.user.nikeName
      }

      var commentList = this.data.commentList;
      oneComment.twoAllQunatity = 0;
      commentList[oneComment] = oneComment.twoCommentResponseList.unshift(newTwoComment);
      this.setData({
        commentList: commentList
      })
      this.addTwoComment(content, id, oneComment.oneCommentContent);
    } else if (type == 3) {
      var id = util.getUUID();
      var twoCommentIndex = this.data.twoCommentIndex;
      //一层评论下标
      var pindex = twoCommentIndex.pindex;
      //二层评论下标
      var index = twoCommentIndex.index;
      //全部评论
      var commentList = this.data.commentList;
      //当前一级评论
      var oneComment = commentList[pindex];
      //当前二级评论
      var towComment = oneComment.twoCommentResponseList[index];
      var data = {
        twoCommentContent: content,
        showCommentDate: "刚刚",
        twoCommentId: id,
        twoCommentUserId: this.data.plainText,
        twoLikeDate: null,
        twoLikeQuantity: 0,
        twoShowLikeQuantity: 0,
        twoOneCommentId: oneComment.oneCommentId,
        twoReplyUserId: towComment.twoCommentId,
        twoReplyUserNikeName: towComment.twoUserNikeName,
        twoUserHeadPortrait: app.globalData.user.headPortrait,
        twoUserNikeName: app.globalData.user.nikeName
      }
      oneComment.twoAllQunatity = 0;
      //一级评论新增二级评论
      oneComment.twoCommentResponseList.unshift(data);
      //刷新当前一级评论
      commentList[pindex] = oneComment;
      this.setData({
        commentList: commentList
      })
      this.addTwoCommentReply(oneComment, towComment, id, content);
    }
  },
  //添加二级评论回复给xxx
  addTwoCommentReply: function(oneComment, towComment, id, content) {
    var that = this;
    //喵文
    var talk = this.data.talk;
    wx.request({
      url: app.globalData.requestUrl + 'addTwoComment',
      method: 'POST',
      data: {
        //一级评论id
        oneCommentId: oneComment.oneCommentId,
        //一级评论作者
        oneCommentUserId: oneComment.oneCommentUserId,
        //原文作者id
        talkUserId: talk.userId,
        //原文id
        talkId: talk.talkId,
        //评论人id
        twoCommentUserId: app.globalData.user.id,
        //评论内容
        commentContent: content,
        //新增二级评论id,前端生成
        id: id,
        //回复给谁
        replyUserId: towComment.twoCommentUserId,
        //关联内容
        ohterContent: towComment.twoCommentContent
      }
    })
  },
  //添加二级评论
  addTwoComment: function(content, id, ohterContent) {
    //一层评论
    var oneComment = this.data.oneComment;
    //喵文
    var talk = this.data.talk;
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'addTwoComment',
      method: 'POST',
      data: {
        //一级评论id
        oneCommentId: oneComment.oneCommentId,
        //一级评论作者
        oneCommentUserId: oneComment.oneCommentUserId,
        //原文作者id
        talkUserId: talk.userId,
        //原文id
        talkId: talk.talkId,
        //评论人id
        twoCommentUserId: app.globalData.user.id,
        //评论内容
        commentContent: content,
        //新增二级评论id,前端生成
        id: id,
        //关联内容
        ohterContent: ohterContent
      }
    })
  },
  //添加一级评论
  addOneComment: function(content, id) {
    var talk = this.data.talk;
    wx.request({
      url: app.globalData.requestUrl + 'addOneComment',
      method: 'POST',
      data: {
        //评论人id
        commentUserId: app.globalData.user.id,
        //喵文作者id
        talkUserId: talk.userId,
        //喵文id
        talkId: talk.talkId,
        //评论内容
        content: content,
        //评论id
        id: id
      }
    })
  },
  //键入文字
  focusInput: function(e) {
    var cursor = e.detail.cursor;
    var value = e.detail.value;
    if (cursor > 50) {
      value = value.substr(0, 50);
    }
    this.setData({
      content: value
    })
  },

  //获取喵文详情
  getTalkInfo: function(id) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getTalkInfo',
      method: 'GET',
      data: {
        talkId: id,
        userId: app.globalData.user.id
      },
      success: function(r) {
        var talk = r.data.data;
        if (r.data.code == 200) {
          if (talk == null) {
            wx.showToast({
              title: '这篇日志在宇宙中失踪了,换一个试试',
              icon: 'none',
              duration: 3000
            })
          } else {
            if (talk.talkDescribe.length > 75) {
              talk.describeOpen = true;
              talk.describeText = '展开'
              talk.showDescribe = talk.talkDescribe.substring(0, 75);
            } else {
              talk.showDescribe = talk.talkDescribe;
              talk.describeOpen = false;
            }
            // if (talk.talkType == '0') {
            //   for (var i of talk.resourceList) {
            //     i.src = i.src + "?x-oss-process=image/resize,m_pad,h_425,w_375";
            //   }
            // }
            talk.showLikeQuantity = util.formatQuantity(talk.likeQuantity);
            talk.showDate = util.formatDate(talk.talkDate);
            talk.showCommentQuantity = util.formatQuantity(talk.commentQuantity);
            that.setData({
              talk: talk
            })

            //获取推荐喵文
            if (talk.label != '') {
              that.getTalkLikeLabel(talk.label, talk.talkId);
            }
            //无评论
            if (talk.commentQuantity == 0) {
              that.setData({
                noComment: false
              })
            } else { //有评论
              that.setData({
                noComment: true
              })
              //查询热门评论
              that.getHotCommentResponseByTalkId();
            }
          }
        } else {
          wx.showToast({
            title: r.data.message,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络连接失败请稍后重试',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },
  //一层评论点赞
  oneLike: function(e) {
    var index = e.currentTarget.dataset.index;
    var commentList = this.data.commentList;
    var comment = commentList[index];
    if (comment.oneLikeDate == null) {
      comment.oneLikeDate = 'A';
      comment.oneLikeQuantity = comment.oneLikeQuantity + 1;
      this.addLikeOneComment(comment, 1);
    } else {
      comment.oneLikeDate = null;
      comment.oneLikeQuantity = comment.oneLikeQuantity - 1;
      this.addLikeOneComment(comment, 2);
    }
    comment.oneShowLikeQuantity = util.formatQuantity(comment.oneLikeQuantity);
    this.setData({
      commentList: commentList
    })
  },
  //加载一层评论
  getOneCommentList: function() {
    var that = this;
    var time = '';
    if (this.data.getOneCount != 0) {
      var commentList = this.data.commentList;
      time = commentList[commentList.length - 1].oneCommentDate
    }
    this.data.getOneCount = this.data.getOneCount + 1;
    wx.request({
      url: app.globalData.requestUrl + 'getCommentResponseByTalkIdNotInHotListOrderByDate',
      method: 'POST',
      data: {
        talkId: that.data.talk.talkId,
        hotIds: that.data.notInOneCommentIds,
        userId: app.globalData.user.id,
        time: time
      },
      success: function(r) {
        if (r.data.code == 200) {
          var list = r.data.data;
          var commentList = that.data.commentList;
          for (var i of list) {
            i.oneShowDate = util.formatDate(i.oneCommentDate);
            i.oneShowLikeQuantity = util.formatQuantity(i.oneLikeQuantity);
            for (var x of i.twoCommentResponseList) {
              x.showCommentDate = util.formatDate(x.twoCommentDate);
              x.twoShowLikeQuantity = util.formatQuantity(x.twoLikeQuantity);
              i.twoAllQunatity = x.twoAllQunatity;
            }
          }
          commentList = commentList.concat(list);
          that.setData({
            commentList: commentList
          })
        } else {
          wx.showToast({
            title: r.data.message,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络连接断开,加载评论失败',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },

  //一层评论点赞请求
  addLikeOneComment: function(comment, type) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'addLikeOneComment',
      method: 'POST',
      data: {
        //评论人id
        commentUserId: comment.oneCommentUserId,
        //点赞人id
        likeCommentUserId: app.globalData.user.id,
        //一层评论id
        talkOneCommentId: comment.oneCommentId,
        //1点赞2取消点赞
        type: type,
        //点赞内容
        content: comment.oneCommentContent,
        //原文id
        talkId: that.data.talk.talkId
      }
    })
  },
  //加载二级评论
  getAllTwoComment: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var oneComment = this.data.commentList[index];
    var twoComments = oneComment.twoCommentResponseList;
    var time = '';
    if (oneComment.getTwoCount != 0) {
      time = twoComments[twoComments.length - 1].twoCommentDate
    }
    oneComment.getTwoCount = oneComment.getTwoCount + 1;
    wx.request({
      url: app.globalData.requestUrl + 'getTwoCommentByOneCommentIdNotInIdOrderByDate',
      method: 'GET',
      data: {
        oneCommentId: oneComment.oneCommentId,
        notTwoId: oneComment.notTwoIds,
        time: time,
        userId: app.globalData.user.id
      },
      success: function(r) {
        if (r.data.code == 200) {
          var twoCommentList = r.data.data;
          for (var i of twoCommentList) {
            i.showCommentDate = util.formatDate(i.twoCommentDate);
            i.twoShowLikeQuantity = util.formatQuantity(i.twoLikeQuantity);
          }
          twoComments = twoComments.concat(twoCommentList);
          that.data.commentList[index].twoCommentResponseList = twoComments;
          that.setData({
            commentList: that.data.commentList
          })
        } else {
          wx.showToast({
            title: r.data.message,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,获取日志回复失败',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },
  //查询热门评论
  getHotCommentResponseByTalkId: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getHotCommentResponseByTalkId',
      method: 'GET',
      data: {
        talkId: that.data.talk.talkId,
        userId: app.globalData.user.id
      },
      success: function(r) {
        if (r.data.code == 200) {
          var notInOneCommentIds = that.data.notInOneCommentIds;
          var commentList = r.data.data;
          for (var i of commentList) {
            i.oneShowDate = util.formatDate(i.oneCommentDate);
            i.oneShowLikeQuantity = util.formatQuantity(i.oneLikeQuantity);
            //排除一级评论
            notInOneCommentIds.push(i.oneCommentId);
            //排除二级评论
            if (i.twoCommentResponseList.length != 0) {
              i.notTwoIds = i.twoCommentResponseList[0].twoCommentId;
              i.twoAllQunatity = i.twoCommentResponseList[0].twoAllQunatity;
              i.getTwoCount = 0;
            } else {
              i.twoAllQunatity = 0;
            }
            for (var x of i.twoCommentResponseList) {
              x.showCommentDate = util.formatDate(x.twoCommentDate);
              x.twoShowLikeQuantity = util.formatQuantity(x.twoLikeQuantity);
            }
          }
          that.setData({
            commentList: commentList,
            notInOneCommentIds: notInOneCommentIds,
            oneAllQuantity: commentList[0].oneAllQuantity
          })
        } else {
          wx.showToast({
            title: r.data.message,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络出现错误,获取日志评论失败',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },
  //二级评论点赞
  twoLike: function(e) {
    var pindex = e.currentTarget.dataset.pindex;
    var index = e.currentTarget.dataset.index;
    var oneComment = this.data.commentList[pindex];
    var twoComment = oneComment.twoCommentResponseList[index];
    var type = 0;
    if (twoComment.twoLikeDate == null) {
      type = 1;
      twoComment.twoLikeDate = 'B';
      twoComment.twoLikeQuantity = twoComment.twoLikeQuantity + 1;
    } else {
      type = 2;
      twoComment.twoLikeDate = null;
      twoComment.twoLikeQuantity = twoComment.twoLikeQuantity - 1;
    }
    twoComment.twoShowLikeQuantity = util.formatQuantity(twoComment.twoLikeQuantity);
    this.setData({
      commentList: this.data.commentList
    })
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + '/addLikeTwoComment',
      method: 'POST',
      data: {
        //二层评论作者id
        twoCommentUserId: twoComment.twoCommentUserId,
        //二层评论id
        twoCommentId: twoComment.twoCommentId,
        //点赞人ID
        likeUserId: app.globalData.user.id,
        // 1点赞 2取消点赞
        type: type,
        content: twoComment.twoCommentContent,
        talkId: that.data.talk.talkId
      }
    })
  },
  //  视频进入全屏
  videoScreen: function(e) {
    var fullScreen = e.detail.fullScreen;
    if (fullScreen) {
      this.setData({
        fullScreen: true
      })
    } else {
      this.setData({
        fullScreen: false
      })
    }
  },
  //关注
  attention: function() {
    var talk = this.data.talk;
    if (talk.attentionDate == null) {
      talk.attentionDate = 'A';
      this.attentionReq(1);
    } else {
      talk.attentionDate = null;
      this.attentionReq(2);
    }
    this.setData({
      talk: talk
    })
  },

  //关注或取消关注
  attentionReq: function(type) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'addAttention',
      method: 'POST',
      data: {
        userId: that.data.talk.userId,
        fansId: app.globalData.user.id,
        type: type
      }
    })
  },

  //获取推荐
  getTalkLikeLabel: function(label, talkId) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getTalkLikeLabel',
      method: 'GET',
      data: {
        label: label,
        talkId: talkId
      },
      success: function(r) {
        var data = r.data.data;
        //左边数组
        var arr1 = [];
        //右边数组
        var arr2 = [];
        for (var i = 0; i < data.length; i++) {
          //转换数字
          data[i].likeQuantity = util.formatQuantity(data[i].likeQuantity);
          //找到图片高度
          data[i].imageHeight = util.getImageHeight(data[i].height, data[i].width, 0.48);
          //如果是视频,则取视频封面
          if (data[i].talkType != 0) {
            data[i].src = data[i].src + "?x-oss-process=video/snapshot,t_1000,f_jpg,w_" + data[i].width + ",h_" + data[i].height + ",m_fast";
          }
          //如果是双数则放到第一个盒子
          if (i % 2 == 0) {
            arr1.push(data[i]);
          } else {
            arr2.push(data[i]);
          }
          that.setData({
            talkList: data,
            talkList1: arr1,
            talkList2: arr2
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '获取日志失败,请下拉重试',
          icon: 'none',
          duration: 30000
        })
      }
    })
  },

  //跳转推荐
  showTalk: function(e) {
    var id = e.detail.currentTarget.dataset.id;
    var label = e.detail.currentTarget.dataset.label;
    var userId = app.globalData.user.id;
    wx.redirectTo({
      url: '/pages/talkInfo/talkInfo?id=' + id + '&label=' + label,
    })
  },
  //举报
  complanin: function(e) {
    var that = this;
    var complaninList = that.data.complaninList
    wx.showActionSheet({
      itemList: complaninList,
      success: function(e) {
        wx.request({
          url: app.globalData.requestUrl + 'complainTalk',
          method: 'POST',
          data: {
            talkId: that.data.talk.talkId,
            userId: app.globalData.user.id,
            complainContent: complaninList[e.tapIndex],
          },
          complete: function() {
            wx.showToast({
              title: '举报成功,我们会尽快对该内容进行审核.感谢您对我们的支持',
              icon: 'none',
              duration: 3000
            })
          }
        })
      }
    })
  },

  //点赞
  likeTalk: function() {
    var talk = this.data.talk;
    if (talk.likeDate == null) {
      //点赞
      this.likeTalkRqu(1);
      //有值红心
      talk.likeDate = 'A';
      //点赞数+1
      talk.likeQuantity = talk.likeQuantity + 1;
      talk.showLikeQuantity = util.formatQuantity(talk.likeQuantity);
    } else {
      //取消点赞
      this.likeTalkRqu(2);
      //无值空心
      talk.likeDate = null;
      //点赞数-1
      talk.likeQuantity = talk.likeQuantity - 1;
      talk.showLikeQuantity = util.formatQuantity(talk.likeQuantity);
    }
    this.setData({
      talk: talk
    })
  },

  //发出请求,点赞或取消点赞
  likeTalkRqu: function(type) {
    var talk = this.data.talk;
    wx.request({
      url: app.globalData.requestUrl + 'likeTalk',
      method: 'POST',
      data: {
        talkId: talk.talkId,
        userId: app.globalData.user.id,
        type: type,
        talkUserId: talk.userId
      }
    })
  },

  //打开或关闭文字描述
  openOrCloseDescribe: function(e) {
    var talk = this.data.talk;
    if (talk.describeText == '展开') {
      talk.describeText = '收起';
      talk.showDescribe = talk.talkDescribe
    } else {
      talk.describeText = '展开';
      talk.showDescribe = talk.talkDescribe.substring(0, 75);
    }
    this.setData({
      talk: talk
    })
  },
  //返回
  rollback: function() {
    wx.navigateBack({
      delta: 1
    })
  },
  //查看他的信息
  readUser: function () {
    var userId = this.data.talk.userId;
    var plainText = app.globalData.user.plainText;
    if (userId == plainText) {
      return;
    }
    wx.navigateTo({
      url: '/pages/readUser/readUser?id=' + userId
    })
  }
})